package com.patternbox.eclipse.wizard;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;

import com.patternbox.eclipse.views.ScenariosView;

public class ScenarioWizard extends Wizard implements INewWizard {

	private AddScenario page;
	
	
	public ScenarioWizard(){
		super();		
		setNeedsProgressMonitor(true);      
		setWindowTitle("Add a new Scenario");
	}
	
	@Override
	public void init(IWorkbench arg0, IStructuredSelection arg1) {
		
	}

	public void addPages() {
		page = new AddScenario();
		addPage(page);
	}
	
	@Override
	public boolean performFinish() {
		
		final String containerName = page.getContainerName();
		final String title = page.getTitleName();
		final String type = page.getTypeName();
		final String description = page.getDescriptionName();

		// Create the content of the file
		
		String EOL = System.getProperty("line.separator");
		String xmlBody = "<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?>" + EOL;
		xmlBody += "<scenario id=\"" + type +"\">" + EOL ;
		xmlBody += "<title>" + title + "</title>" + EOL;
		xmlBody += "<description>" + description + "</description>" + EOL;
		xmlBody += "</scenario>";

		// Get the current path
		
		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		IResource resource = root.findMember(new Path(containerName));
		IContainer container = (IContainer) resource;
		
		// Create the file if it doesn't exist
		final IFile file = container.getFile(new Path(title + ".sce"));
        InputStream stream = new ByteArrayInputStream(xmlBody.getBytes());
		try{
			if (file.exists()) {		
				file.setContents(stream, true, true, null);
			} else {
				file.create(stream, true, null);
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
		IViewPart view = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView("com.patternbox.eclipse.views.ScenariosView");
		if (view != null)
			((ScenariosView) view).refreshView();
		
		return true;
	}
	

}
